package jp.co.dailyReport;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import org.apache.log4j.Logger;

/**
 * DBへ接続処理するクラスです。
 */
public class DB {

	private static Logger log = Logger.getLogger(DB.class);

	private static final String DB_DRIVER = Globals.get("DB_DRIVER");
	private static final String DB_URL_PRIMARY = Globals.get("DB_URL_PRIMARY");
	private static volatile boolean initDriver;
	private static byte lock[] = new byte[0];
	private static final int MAX_RETRY = 3;

	public DB() {}

	/**
	 * DBへのコネクションを返します。
	 * 
	 * @return Connection
	 * @throws SQLException
	 */
	public static Connection getConnectionPrimary() throws SQLException {

		Connection conn = null;
		synchronized(lock) {
			if(!initDriver) {
				log.info("initialize driver...");
				try {
					Class.forName(DB_DRIVER).newInstance();
				} catch(ClassNotFoundException cnfe) {
					log.error(cnfe.toString(), cnfe);
					return null;
				} catch(InstantiationException ie) {
					log.error(ie.toString(), ie);
					return null;
				} catch(IllegalAccessException iae) {
					log.error(iae.toString(), iae);
					return null;
				}
				log.info("OK (initialize driver)");
				initDriver = true;
			}
		}
		for(int retry = 0; conn == null && ++retry <= 3; conn = DriverManager.getConnection(DB_URL_PRIMARY)) {
			if(retry > 1)
				try {
					Thread.sleep(700L);
				} catch(InterruptedException interruptedexception) { }
			log.debug("get connection to primary(" + retry + ")");
		}
		if(conn == null) {
			log.fatal("cannot get connection to primary");
			throw new RuntimeException("cannot get connection to primary");
		} else {
			return conn;
		}
	}
}